 <!--
* description: 门店级别系数
* author: wangjuan
* createdDate: 2020-11-17
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import api from "@/api/se/apiBaseData";
import api1 from "@/api/subsidyManage";
import Vue from "vue";
import { vehiclePdiPriceInquirys } from "@/api/se/vehiclePdiPriceInquiry";
import request from "@/utils/request";
import { managements } from '@/api/se/bookingManagement'

export default {
  name: "StoreLevelFactor",

  components: {
    OneTableTemplate,
    Edit: () => import("./edit"),
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function () {
      next();
    });
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      // 网格查询API配置对象
      apiConfig: vehiclePdiPriceInquirys.queryDlrParamSet,
      editRowData: {},
      selectData: {},
      editPopupsVisible: false,
      titleName: "区域审核",
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          name: "search",
          clickEvent: () => this.queryTable(1),
          text: this.$t("sys.button.query"), // 查询
          position: "right",
          fuzzySearch: true,
        },
        // {
        //   compKey: "btnKey4",
        //   type: "",
        //   size: "small",
        //   name: "reset",
        //   clickEvent: () => this.reset(),
        //   text: this.$t("sys.button.reset"),
        //   position: "right" // 重置
        // },
        {
          compKey: "btnKey4",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: "重置",
          position: "right", // 重置
        },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          name: "importTemplate",
          position: "upload",
          clickEvent: () => this.handFileListChange(),
          text: "导入",
        },
        {
          compKey: "btnKey3",
          type: "text",
          size: "small",
          name: "",
          position: "upload",
          click: (event) => {
            this.templateDownload();
          },
        },
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              {
                compKey: "compKey2",
                labelName: "大区：",
                codeField: "bigAreaName",
                textField: "bigAreaName",
                component: () => import("@/components/org/LookupValue"),
                oFields: "bigAreaId,bigAreaName",
                options: [{ bigAreaId: "", bigAreaName: "" }],
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey3",
                labelName: "省份：",
                codeField: "provinceId",
                textField: 'provinceName',
                component: () => import('@/components/org/commonSelect'),
                customObj: {
                  api: managements.queryProvince,
                  selectType: '1'
                },
                oFields: "provinceId,provinceName",
                type: 'dropdownList',
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "城市：",
                codeField: "cityId",
                textField: "cityName",
                oFields: 'cityId,cityName',
                component: () => import('@/components/org/commonSelect'),
                customObj: {
                  api: managements.queryCityList,
                  listQuery: {
                    provinceId: ''
                  },
                  selectType: '1'
                },
                parentFileds: 'value:provinceId',
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey5",
                labelName: "门店级别：",
                codeField: "dlrLevel",
                component: () => import("@/components/org/commonSelect"),
                customObj: {
                  api: vehiclePdiPriceInquirys.repairType,
                },
                oFields: "lookupValueCode,lookupValueName",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "门店编码：",
                codeField: "dlrCode",
                component: () => import("@/components/ve/multipleSearchInput"),
                type: "inputText",
                isMust: false,
                isMul: false,
                dataToObject: {
                  // 控制弹窗页面 搜索 网格 元素
                  tableComponents: [
                    {
                      compKey: "compKey1",
                      labelName: "门店编码：",
                      codeField: "dlrCode",
                      component: () => import("@/components/org/commonInput"),
                      type: "inputText",
                      isMust: true,
                      span: 8,
                    },
                    {
                      compKey: "compKey2",
                      labelName: "门店名称：",
                      codeField: "dlrName",
                      component: () => import("@/components/org/commonInput"),
                      type: "inputText",
                      isMust: true,
                      span: 8,
                    },
                  ],
                  tableCols: [
                    {
                      prop: "dlrCode",
                      label: "门店编码",
                    },
                    {
                      prop: "dlrName",
                      label: "门店名称",
                    },
                  ],
                  formField: {
                    dlrCode: "",
                    dlrName: "",
                  },
                  returnField: {
                    prop: "dlrCode",
                    label: "门店编码",
                  },
                  api: api.findDlr,
                },
                span: 6,
              },
              {
                compKey: "compKey7",
                labelName: "门店类别：",
                codeField: "dlrType",
                component: () => import("@/components/org/LookupValue"),
                oFields: "statusId,statusText",
                options: [
                  { statusId: "1", statusText: "直营店" },
                  { statusId: "2", statusText: "授权店" },
                ],
                type: "dropdownList",
                isMul: false,
                isMust: false,
              },
            ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "subsidyId",
                label: "主键ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "controlBtn",
                label: "操作",
                width: 100,
                fixed: true,
                isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "修改",
                    component: () => import("@/components/org/linkButton"),
                    clickEvent: (index) => this.edit(index),
                  },
                ],
              },
              {
                prop: "bigAreaName",
                label: "大区",
              },
              // {
              //   prop: "cityName",
              //   label: "分区",
              // },
              {
                prop: "provinceName",
                label: "省份",
              },
              {
                prop: "cityName",
                label: "城市",
              },
              {
                prop: "dlrCode",
                label: "门店编码",
              },
              {
                prop: "dlrFullName",
                label: "门店名称",
              },
              {
                prop: "dlrTypeCn",
                label: "门店类别",
              },
              {
                prop: "dlrLevelCn",
                label: "门店级别",
              },
              {
                prop: "pdiCoef",
                label: "PDI价格系数",
              },
              {
                prop: "claimWiCoef",
                label: "索赔工时系数",
              },
              {
                prop: "claimPartCoef",
                label: "索赔备件系数",
              },
              {
                prop: "balanceWiCoef",
                label: "结算工时系数",
              },
              {
                prop: "discountWi",
                label: "工时授权折扣",
              },
              {
                prop: "discountPart",
                label: "备件授权折扣",
              },
              {
                prop: "discountOrder",
                label: "工单授权折扣",
              },
              {
                prop: "isFirstMaintainCn",
                label: "是否允许首保",
              },
              {
                prop: "isRepairCn",
                label: "是否允许保修",
              },
              {
                prop: "isActivesCn",
                label: "是否允许权益",
              },
              {
                prop: "isEnableCn",
                label: "状态",
              },
            ],

      // 表单数据
      formField: this.$utils.getFormField(
        this,
        {
          bigAreaName: "",
          provinceId: "",
          cityId: "",
          dlrLevel: "",
          dlrCode: "",
          dlrType: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
    };
  },

  mounted() {
    // 列表查询
    this.queryTable(1);
    this.bigAreaSelectQuery();
  },
  watch: {
    // "formField.provinceId": {
    //   handler: function (Val) {
    //     if (Val) {
    //       this.tableComponents[2].options = [];
    //       const info = {};
    //       info.provinceId = this.formField.provinceId;
    //       request({
    //         url: vehiclePdiPriceInquirys.listOfCities.APIUrl,
    //         method: "post",
    //         data: info,
    //       }).then((res) => {
    //         res.rows.map((item) => {
    //           this.tableComponents[2].options.push({
    //             label: item.cityName,
    //             value: item.cityId,
    //           });
    //         });
    //       });
    //     }
    //   },
    // },
  },
  methods: {
    edit(index) {
      this.editPopupsState = "edit";
      this.editPopupsVisible = true;
      this.editRowData = this.$refs["multipleTable"].list[index];
    },
    close() {
      this.editPopupsVisible = false;
      this.queryTable(1);
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime("门店级别系数.xlsx");
      this.$requestAPI({
        apiUrl: "/mp/e3sh/aftersale/DlrParamSetService/downloadTemplate.do",
        variables: { dataType: "excel" },
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file);
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning",
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const that = this;
      const url = "/mp/e3sh/aftersale/DlrParamSetService/importDlrParamSet.do";
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close();
          if (response.result === "1") {
            this.$message({
              message: "导入成功",
              type: "success",
            });
            that.queryTable();
          } else {
            this.$message({
              message: response.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {});
    },
    // 大区下拉框
    bigAreaSelectQuery() {
      const bigAreaSelect = [];
      const queryObj = {
        // api配置
        apiConfig: api1.listOfRegion,
        // 表格中台返回网格的字段
        apiQueryRow: ["bigAreaId", "bigAreaName"],

        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.formField,
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          const list = response.rows;
          for (const k in list) {
            bigAreaSelect.push({
              bigAreaId: list[k].bigAreaId,
              bigAreaName: list[k].bigAreaName,
            });
          }
          for (const k in this.tableComponents) {
            if (this.tableComponents[k].codeField === "bigAreaName") {
              this.tableComponents[k].options = bigAreaSelect;
              return false;
            }
          }
        } else {
          this.$message({
            message: response.msg,
            type: "warning",
            duration: 2000,
          });
        }
      });
    },
  },
};
</script>
